package com.yzs.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.power.common.util.RandomUtil;
import com.yzs.common.bean.R;
import com.yzs.entity.ForgetPwd;
import com.yzs.entity.User;
import com.yzs.mapper.UserMapper;
import com.yzs.service.IUserService;
import com.yzs.service.RedisService;
import com.yzs.utils.EmailUtil;
import com.yzs.utils.JwtUtil;
import com.yzs.utils.MD5Util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtUtil JwtUtil;
    @Autowired
    EmailUtil emailUtil;
    @Autowired
    RedisService redisService;

    @Override
    public R registerUser(User u) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", u.getUsername()).or();
        User user = userMapper.selectOne(userQueryWrapper);
        if (user != null) {
            return R.error("用户名已存在，请重新输入！");
        }else {
            user = null;
            userQueryWrapper.clear();
            userQueryWrapper.eq("email", u.getEmail());
            user = userMapper.selectOne(userQueryWrapper);
            if(user != null){
                return R.error("邮箱已存在，请重新输入！");
            }
        }
        int i = userMapper.insert(u);
        if (i == 1) {
            return R.ok("注册成功,请前登录！");
        }
        return R.error("注册失败！");
    }

    @Override
    public R loginUser(User u) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", u.getUsername()).eq("password", u.getPassword());
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            return R.error("用户名或密码错误！");
        }
        String userToken = JwtUtil.createUserToken(user);
        if (Objects.isNull(userToken)) {
            return R.error("登录失败！");
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("name", user.getName());
        map.put("id", user.getId().toString());
        map.put("token", userToken);
        return R.ok("登录成功！", map);
    }

    @Override
    public R getUserInfo(String token) {
        return null;
    }

    @Override
    public R getSalerById(Integer id) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("name", "phone").eq("id", id);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user != null) {
            return R.ok(user);
        }
        return R.error();
    }

    @Override
    public R changePwd(String oldPwd, String newPwd, String token) {
        String username = null;
        try {
            username = String.valueOf(JwtUtil.getTokenUserInfo(token).getBody().get("username"));
        } catch (Exception e) {
            return R.error();
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username).eq("password", oldPwd);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            return R.error("输入的旧密码不正确，请重新输入！");
        }
        if (oldPwd.equals(newPwd)) {
            return R.error("旧密码不能和新密码一样!");
        }
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.set("password", newPwd).eq("username", username).eq("password", oldPwd);
        int update = userMapper.update(null, userUpdateWrapper);
        if (update == 1) {
            return R.ok("修改成功，请重新登录！");
        }
        return R.error("修改失败");
    }

    @Override
    public R getVerifyCode(String name) {
        String email = null;
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", name).or().eq("email",name);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            return R.error("用户名或邮箱不存在，请重新输入！");
        } else {
            email = user.getEmail();
        }
        // 设置验证码，可以自己随机生成
        String code = RandomUtil.randomString(6);
        String tips = emailUtil.sendEmailVerifyCode(code, "mappleid0614@163.com", email);
        if ("验证码发送成功！".equals(tips)) {
            return R.ok(tips);
        } else {
            return R.error(tips);
        }
    }

    @Override
    public R forgetPwd(ForgetPwd forgetPwd) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",forgetPwd.getUsername()).or().eq("email",forgetPwd.getUsername());
        User user = userMapper.selectOne(userQueryWrapper);
        if(user == null){
            return R.error("用户名或邮箱不存在，请重新输入！");
        }
        String verifyCode = (String) redisService.get("VerifyCode_" + user.getEmail());
        if (Objects.isNull(verifyCode)){
            return R.error("验证码已过期，请重新获取！");
        }
        if(!verifyCode.equals(forgetPwd.getVerifyCode())){
            return R.error("验证码错误，请重新输入！");
        }
        if(user.getPassword().equals(forgetPwd.getPassword())){
            return R.error("新密码不能和旧密码相同！");
        }
        user.setPassword(forgetPwd.getPassword());
        int i = userMapper.updateById(user);
        if(i == 1){
            return R.ok("重置密码成功，请登录！");
        }
        return R.error("重置密码失败，请重试！");
    }

}
